package org.sam.swing.template.dialog;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;

import org.sam.swing.JSDialog;

/**
 * 操作对话框模板
 * 
 * @author sam
 *
 */
public abstract class JProcessModelDialog extends JSDialog {

	private static final long serialVersionUID = 9069738509339968957L;

	/**
	 * 时钟对象
	 */
	private Timer timer;

	private JButton btnOK;

	private JButton btnCancel;

	private JProgressBar processBar;

	/**
	 * 导入dxf文件的向导窗口
	 */
	public JProcessModelDialog() {
		this(true);
	}

	/**
	 * 自动初始化
	 * 
	 * @param autoInit
	 */
	public JProcessModelDialog(boolean autoInit) {
		if (autoInit) {
			this.init();
		}
	}

	/**
	 * 初始化
	 */
	protected void init() {
		this.setLayout(new BorderLayout());

		JPanel buttons = this.initButtons();
		if (buttons != null) {
			this.add(buttons, BorderLayout.SOUTH);
		}

		timer = new Timer(500, e -> {
			processBar.setValue(processBar.getValue() + 1);
		});

		JPanel center = initCompents();
		if (center != null) {
			add(center, BorderLayout.CENTER);
		}
	}

	/**
	 * 初始化空间显示
	 */
	protected abstract JPanel initCompents();

	/**
	 * 生成工具按钮
	 * 
	 * @return
	 */
	protected JPanel initButtons() {
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		btnOK = new JButton("确定");
		btnOK.setName("btnOK");
		btnOK.addActionListener(e -> {
			this.setAction(OK);
		});

		btnCancel = new JButton("取消");
		btnCancel.setName("btnCancel");
		btnCancel.addActionListener(e -> {
			this.setAction(CANCEL);
			this.setVisible(false);
		});

		// 生成进度条对象
		processBar = new JProgressBar();
		processBar.setName("processBar");
		processBar.setMaximum(100);
		processBar.setMinimum(1);
		processBar.setValue(1);
		processBar.setVisible(false);

		panel.add(processBar);
		panel.add(btnOK);
		panel.add(btnCancel);
		return panel;
	}

	/**
	 * 开启进度条
	 */
	public void startProcess() {
		processBar.setVisible(true);
		btnOK.setText("执行中");
		btnOK.setEnabled(false);
		btnCancel.setEnabled(false);
		timer.start();
	}

	/**
	 * 停止进度条
	 */
	public void stopProcess() {
		btnOK.setText("确定");
		btnOK.setEnabled(true);
		btnCancel.setEnabled(true);
		processBar.setValue(0);
		processBar.setVisible(false);
		timer.start();
	}
}
